﻿using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using StackExchange.Profiling;

namespace MT.WebApi.Core.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly IHostingEnvironment _env;
        private readonly ILogger<GlobalExceptionFilter> _logger;
        //  private readonly IHubContext<ChatHub> _hubContext;

        public GlobalExceptionFilter(IHostingEnvironment env, ILogger<GlobalExceptionFilter> logger
            //,IHubContext<ChatHub> hubContext
            )
        {
            _env = env;
            _logger = logger;
            //  _hubContext = hubContext;
        }

        public void OnException(ExceptionContext context)
        {
            var json = new JsonErrorResponse {Message = context.Exception.Message};

            if (_env.IsDevelopment())
            {
                json.DevelopmentMessage = context.Exception.StackTrace;
            }
            context.Result = new InternalServerErrorObjectResult(new { Code=500,Msg= context.Exception.Message , DevelopmentMessage = context.Exception.StackTrace });

            MiniProfiler.Current.CustomTiming("Errors：", json.Message);
            
            _logger.LogError(json.Message, WriteLog(json.Message, context.Exception));

            //_hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();

        }

        /// <summary>
        /// 自定义返回格式
        /// </summary>
        /// <param name="throwMsg"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        public string WriteLog(string throwMsg, Exception ex)
        {
            return string.Format("【自定义错误】：{0} \r\n【异常类型】：{1} \r\n【异常信息】：{2} \r\n【堆栈调用】：{3}", new object[] { throwMsg,
                ex.GetType().Name, ex.Message, ex.StackTrace });
        }

    }
    public class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object value) : base(value)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
    //返回错误信息
    public class JsonErrorResponse
    {
        /// <summary>
        /// 生产环境的消息
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 开发环境的消息
        /// </summary>
        public string DevelopmentMessage { get; set; }
    }
}
